package com.mj.mafeed.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.mj.mafeed.R;
import com.mj.mafeed.bean.ForumTopicJSON;
import com.mj.mafeed.bean.MemberJSON;
import com.mj.mafeed.bean.ForumTopicJSON.ForumTopicImage;
import com.mj.mafeed.service.ForumTopicService;
import com.mj.mafeed.util.DateUtils;
import com.mj.mafeed.util.HttpUtils;
import com.mj.mafeed.util.NetUtils;
import com.mj.mafeed.util.SPUtils;
import com.mj.mafeed.widget.LoadingDialog;
import com.mj.mafeed.widget.MyGridView;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SimpleAdapter.ViewBinder;

/**
 * 资讯详情
 * @author zhaominglei
 * @date 2016-4-8
 * 
 */
public class ForumTopicDetailActivity extends Activity implements OnClickListener {
	@SuppressWarnings("unused")
	private static final String TAG = ForumTopicDetailActivity.class.getSimpleName();
	private ForumTopicService forumTopicService = new ForumTopicService();
	private ImageView goHome;
	@SuppressWarnings("unused")
	private ProgressBar progressBar;
	private ImageView headpic;
	private TextView forumtopicUsername; //用户名
	private TextView forumtopicCreatedate; //时间
	private TextView forumtopicContent; //内容
	private TextView forumtopicPraises; //赞次数
	private TextView forumtopicReplies; //评论次数
	private ImageView forumtopicPraise; //赞
	private ImageView forumtopicReply; //评论
	private RelativeLayout forumtopicRelative3; //评论明细
	private MyGridView gridView; //图片视图
	private Bitmap bitmap; //导入图片
	private ArrayList<HashMap<String, Object>> imageItem;
	private SimpleAdapter simpleAdapter;
	@SuppressWarnings("unused")
	private String referer; // 来自那个链接
	private String username; //用户名
	private String sign; //签名
	private LoadingDialog loadingDialog; //加载框
	private Dialog dialog; //评论对话框
	private EditText commentContentEdt; //评论
	private Button sendBtn; //发送
	private ForumTopicJSON forumTopicJSON;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_forumtopic_detail);
		init();
	}

	private void init() {
		goHome = (ImageView) findViewById(R.id.forumtopic_detail_gohome);
		progressBar = (ProgressBar)findViewById(R.id.forumtopic_detail_progress);
		headpic = (ImageView)findViewById(R.id.forumtopic_detail_headpic);
		forumtopicUsername = (TextView)findViewById(R.id.forumtopic_detail_username);
		forumtopicCreatedate = (TextView)findViewById(R.id.forumtopic_detail_createdate);
		forumtopicContent = (TextView)findViewById(R.id.forumtopic_detail_content);
		forumtopicPraises = (TextView)findViewById(R.id.forumtopic_detail_praises);
		forumtopicReplies = (TextView)findViewById(R.id.forumtopic_detail_replies);
		forumtopicPraise = (ImageView)findViewById(R.id.forumtopic_detail_praise);
		forumtopicReply = (ImageView)findViewById(R.id.forumtopic_detail_reply);
		forumtopicRelative3 = (RelativeLayout)findViewById(R.id.forumtopic_detail_relative3);
		gridView = (MyGridView)findViewById(R.id.forumtopic_detail_gridView);
		
		goHome.setOnClickListener(this);
		forumtopicPraise.setOnClickListener(this);
		forumtopicReply.setOnClickListener(this);
		loadingDialog = new LoadingDialog(this);
		
		referer = getIntent().getStringExtra("referer");
		username = (String)SPUtils.get(getApplicationContext(), "username", "");
		sign = (String)SPUtils.get(getApplicationContext(), "sign", "");
		forumTopicJSON = (ForumTopicJSON)getIntent().getSerializableExtra("forumTopicJSON");
		if (forumTopicJSON == null) {
			Toast.makeText(getApplicationContext(), R.string.like_net_error, Toast.LENGTH_SHORT).show();
			finish();
			return;
		}
		headpic.setBackgroundResource(R.drawable.user_icon);
		forumtopicUsername.setText(forumTopicJSON.getMemberJSON().getUsername());
		forumtopicCreatedate.setText(DateUtils.getDateTime(DateUtils.datePattern, forumTopicJSON.getCreateDate()));
		forumtopicContent.setText(forumTopicJSON.getContent());
		List<ForumTopicJSON.ForumTopicImage> forumTopicImages = forumTopicJSON.getForumTopicImages();
		if (forumTopicImages != null && !forumTopicImages.isEmpty()) {
			imageItem = new ArrayList<HashMap<String,Object>>();
			for (ForumTopicImage forumTopicImage : forumTopicImages) {
				if (forumTopicImage.getSource() == null || forumTopicImage.getSource().equals("")) continue;
				bitmap = HttpUtils.returnBitMap(forumTopicImage.getSource());
				HashMap<String,Object> map = new HashMap<String, Object>();
				map.put("itemImage", bitmap);
				imageItem.add(map);
				simpleAdapter = new SimpleAdapter(getApplicationContext(), imageItem, R.layout.griditem_addpic, new String[]{ "itemImage" }, new int[]{ R.id.griditem_addpic });
				simpleAdapter.setViewBinder(new ViewBinder() {
					@Override
					public boolean setViewValue(View view, Object data,
							String textRepresentation) {
						if (view instanceof ImageView && data instanceof Bitmap) {
							ImageView imageView = (ImageView)view;
							imageView.setImageBitmap((Bitmap)data);
							return true;
						}
						return false;
					}
				});
				gridView.setAdapter(simpleAdapter);
			}
		}
		if (forumTopicJSON.getForumTopicPraises() != null && !forumTopicJSON.getForumTopicPraises().isEmpty()) {
			forumtopicPraises.setText(forumTopicJSON.getForumTopicPraises().size()+"次赞");
			for (ForumTopicJSON.ForumTopicPraise forumTopicPraise : forumTopicJSON.getForumTopicPraises()) {
				MemberJSON memberJSON = forumTopicPraise.getMemberJSON();
				if (memberJSON != null && username != null && username.equals(memberJSON.getUsername())) {
					forumtopicPraise.setImageResource(R.drawable.news_liked);
				}
			}
		}
		if (forumTopicJSON.getReplyCount() != null && forumTopicJSON.getReplyCount().intValue() > 0) {
			forumtopicReplies.setText(forumTopicJSON.getReplyCount()+"次评论");
		}
		if (forumTopicJSON.getForumReplies() != null && !forumTopicJSON.getForumReplies().isEmpty()) {
			for (int i = 0; i < forumTopicJSON.getForumReplies().size(); i++) {
				ForumTopicJSON.ForumReply forumReply = forumTopicJSON.getForumReplies().get(i);
				TextView forumReplyMember = new TextView(this);
				forumReplyMember.setTextColor(getResources().getColor(R.color.forumReplyMember_color));
				forumReplyMember.setText(forumReply.getMemberJSON().getName()+":");
				forumReplyMember.setId((i*2+1));
				TextView forumReplyContent = new TextView(this);
				forumReplyContent.setTextColor(getResources().getColor(R.color.black));
				forumReplyContent.setText(forumReply.getContent());
				
				RelativeLayout.LayoutParams layoutParams0 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
				if (i > 0) {
					layoutParams0.addRule(RelativeLayout.BELOW, (i*2-1));
				}
				forumtopicRelative3.addView(forumReplyMember, layoutParams0);
				RelativeLayout.LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
				if (i > 0) {
					layoutParams1.addRule(RelativeLayout.BELOW, (i*2-1));
				}
				layoutParams1.addRule(RelativeLayout.RIGHT_OF, (i*2+1));
				forumtopicRelative3.addView(forumReplyContent, layoutParams1);
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.forumtopic_detail_gohome:
			finish();
			break;
		
		case R.id.forumtopic_detail_praise:
			if (forumTopicJSON != null) {
				if (username != null && !username.equals("") && sign != null && !sign.equals("")) {
					forumtopicPraise(v, forumTopicJSON);
				} else {
					Toast.makeText(getApplicationContext(), R.string.check_login_error, Toast.LENGTH_SHORT).show();
				}
			}
			break;
			
		case R.id.forumtopic_detail_reply:
			if (forumTopicJSON != null) {
				if (username != null && !username.equals("") && sign != null && !sign.equals("")) {
					showDialogBottom(v, forumTopicJSON);
				} else {
					Toast.makeText(getApplicationContext(), R.string.check_login_error, Toast.LENGTH_SHORT).show();
				}
			}
			break;	
			
		default:
			break;
		}
	}

	private void forumtopicPraise(View v, ForumTopicJSON forumTopicJSON) {
		if (NetUtils.isConnected(getApplicationContext())) {
			loadingDialog.show();
			new ForumTopicDetailPraiseAsyncTask().execute(forumTopicJSON.getForumTopicId().toString());
		} else {
			Toast.makeText(getApplicationContext(), R.string.net_error, Toast.LENGTH_SHORT).show();
		}
	}
	
	@SuppressLint("InflateParams")
	private void showDialogBottom(View v,final ForumTopicJSON forumTopicJSON) {
		dialog = new Dialog(this);
		LayoutInflater inflater = getLayoutInflater();
		View dialogView = inflater.inflate(R.layout.dialog_comment, null);
		commentContentEdt = (EditText)dialogView.findViewById(R.id.dialog_comment_content);
		sendBtn = (Button)dialogView.findViewById(R.id.dialog_comment_send); //评论发送
		
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(dialogView);
		Window window = dialog.getWindow();  
	    window.setGravity(Gravity.BOTTOM);  //设置dialog显示的位置  
	    window.setWindowAnimations(R.style.dialogBottom); //添加动画
	    dialog.show();
	    Display display = getWindowManager().getDefaultDisplay();
	    WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.width = (int) (display.getWidth());
	    dialog.getWindow().setAttributes(layoutParams);
	    
	    sendBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String content = commentContentEdt.getText().toString();
				if (content == null || content.equals("")) {
					Toast.makeText(getApplicationContext(), R.string.dialog_comment_content_hint, Toast.LENGTH_SHORT).show();
					return;
				}
				if (forumTopicJSON != null) {
					if (username != null && !username.equals("") && sign != null && !sign.equals("")) {
						forumtopicComment(v, forumTopicJSON, content);
						dialog.dismiss();
						commentContentEdt.setText("");
					} else {
						Toast.makeText(getApplicationContext(), R.string.check_login_error, Toast.LENGTH_SHORT).show();
					}
				}
			}
		});
	}

	private void forumtopicComment(View v, ForumTopicJSON forumTopicJSON, String content) {
		if (NetUtils.isConnected(getApplicationContext())) {
			loadingDialog.show();
			new ForumTopicDetailCommentAsyncTask().execute(forumTopicJSON.getForumTopicId().toString(), content);
		} else {
			Toast.makeText(getApplicationContext(), R.string.net_error, Toast.LENGTH_SHORT).show();
		}
	}
	
	@Override
	public void onBackPressed() {
		finish();
	}
	
	public class ForumTopicDetailPraiseAsyncTask extends AsyncTask<String, String, ForumTopicJSON> {
		@Override
		protected ForumTopicJSON doInBackground(String... params) {
			return forumTopicService.praise("ForumTopicDetailActivity", params[0], username, sign);
		}
		@Override
		protected void onPostExecute(ForumTopicJSON result) {
			loadingDialog.dismiss();
			if (result != null) {
				if (result.getForumTopicPraises() != null && !result.getForumTopicPraises().isEmpty()) {
					forumtopicPraises.setText(result.getForumTopicPraises().size()+"次赞");
					for (ForumTopicJSON.ForumTopicPraise forumTopicPraise : result.getForumTopicPraises()) {
						MemberJSON memberJSON = forumTopicPraise.getMemberJSON();
						if (memberJSON != null && username != null && username.equals(memberJSON.getUsername())) {
							forumtopicPraise.setImageResource(R.drawable.news_liked);
						}
					}
				}
				Toast.makeText(getApplicationContext(), R.string.praise_success, Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(getApplicationContext(), R.string.praise_error, Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	public class ForumTopicDetailCommentAsyncTask extends AsyncTask<String, String, ForumTopicJSON> {
		@Override
		protected ForumTopicJSON doInBackground(String... params) {
			return forumTopicService.comment("ForumTopicDetailActivity", params[0], params[1], username, sign);
		}

		@Override
		protected void onPostExecute(ForumTopicJSON result) {
			loadingDialog.dismiss();
			if (result != null) {
				if (result.getReplyCount() != null && result.getReplyCount().intValue() > 0) {
					forumtopicReplies.setText(result.getReplyCount()+"次评论");
				}
				if (result.getForumReplies() != null && !result.getForumReplies().isEmpty()) {
					for (int i = 0; i < result.getForumReplies().size(); i++) {
						ForumTopicJSON.ForumReply forumReply = result.getForumReplies().get(i);
						TextView forumReplyMember = new TextView(getApplicationContext());
						forumReplyMember.setTextColor(getResources().getColor(R.color.forumReplyMember_color));
						forumReplyMember.setText(forumReply.getMemberJSON().getName()+":");
						forumReplyMember.setId((i*2+1));
						TextView forumReplyContent = new TextView(getApplicationContext());
						forumReplyContent.setTextColor(getResources().getColor(R.color.black));
						forumReplyContent.setText(forumReply.getContent());
						
						RelativeLayout.LayoutParams layoutParams0 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
						if (i > 0) {
							layoutParams0.addRule(RelativeLayout.BELOW, (i*2-1));
						}
						forumtopicRelative3.addView(forumReplyMember, layoutParams0);
						RelativeLayout.LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
						if (i > 0) {
							layoutParams1.addRule(RelativeLayout.BELOW, (i*2-1));
						}
						layoutParams1.addRule(RelativeLayout.RIGHT_OF, (i*2+1));
						forumtopicRelative3.addView(forumReplyContent, layoutParams1);
					}
				}
				Toast.makeText(getApplicationContext(), R.string.comment_success, Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(getApplicationContext(), R.string.comment_error, Toast.LENGTH_SHORT).show();
			}
		}
	}	
}
